﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using TjZheng.Framework;

namespace TjZheng.JiaLi.Process
{
    public class wwwxiummccProcessHandler : TicketProcessHandler
    {
        protected override SourceInfo GetSourceInfo(JiaLiContext objJiaLiContext, string sourceUrl)
        {
            if (sourceUrl.IsNull())
            {
                throw new ArgumentNullException("sourceUrl");
            }
            SourceInfo objSourceInfo = null;
            if (objJiaLiContext.IsStop)
            {
                return objSourceInfo;
            }
            HtmlWeb objHtmlWeb = new HtmlWeb();
            objHtmlWeb.OverrideEncoding = Encoding.GetEncoding("utf-8");
            HtmlAgilityPack.HtmlDocument objHtmlDocument = objHtmlWeb.Load(sourceUrl);
            if (objHtmlWeb.StatusCode != HttpStatusCode.OK)
            {
                return objSourceInfo;
            }
            HtmlNode objHtmlNode = objHtmlDocument.GetElementbyId("bodywrap");
            if (objHtmlNode == null)
            {
                return objSourceInfo;
            }
            var objHtmlNodeCollection = objHtmlNode.SelectNodes(".//div[@class='pic_box']");
            if (objHtmlNodeCollection.IsNull())
            {
                return objSourceInfo;
            }
            string title = objHtmlNode.SelectSingleNode(".//div[@class='inline']").InnerText.Trim();
            title = title.IsNoNull() ? title : DateTime.Now.ToString("yyyyMMddHHmmss");
            objSourceInfo = new SourceInfo
            {
                SourceUrl = sourceUrl,
                PageTitle = title,
                ImageInfos = new List<ImageInfo>(),
                HtmlDocument = objHtmlDocument
            };
            string str = null;
            HtmlNode objImgHtmlNode = null;
            foreach (var obj in objHtmlNodeCollection)
            {
                objImgHtmlNode = obj.SelectSingleNode(".//img");
                if (objImgHtmlNode == null)
                {
                    continue;
                }
                str = objImgHtmlNode.GetAttributeValue("src", "");
                if (str.IsNull())
                {
                    continue;
                }
                objSourceInfo.ImageInfos.Add(new ImageInfo
                {
                    SourceInfo = objSourceInfo,
                    ImageUrl = str.IndexOf(":") < 0 ? string.Format("http://www.xiumm.cc{0}", str) : str
                });
            }
            return objSourceInfo;
        }

        protected override TargetInfo GetTargetInfo(JiaLiContext objJiaLiContext, string targetUrl)
        {
            if (targetUrl.IsNull())
            {
                throw new ArgumentNullException("targetUrl");
            }
            TargetInfo objTargetInfo = null;
            if (objJiaLiContext.IsStop)
            {
                return objTargetInfo;
            }
            HtmlWeb objHtmlWeb = new HtmlWeb();
            objHtmlWeb.OverrideEncoding = Encoding.GetEncoding("utf-8");
            HtmlAgilityPack.HtmlDocument objHtmlDocument = objHtmlWeb.Load(targetUrl);
            if (objHtmlWeb.StatusCode != HttpStatusCode.OK)
            {
                return objTargetInfo;
            }
            var objHtmlNodeCollection = objHtmlDocument.DocumentNode.SelectNodes("//div[@class='pic_box']");
            if (objHtmlNodeCollection.IsNull())
            {
                return objTargetInfo;
            }
            objTargetInfo = new TargetInfo
            {
                SourceUrl = targetUrl,
                CatchUrls = new List<string>()
            };
            string href = "";
            HtmlNode objHtmlNode = null;
            foreach (var obj in objHtmlNodeCollection)
            {
                objHtmlNode = obj.SelectSingleNode(".//a");
                if (objHtmlNode == null)
                {
                    continue;
                }
                href = objHtmlNode.GetAttributeValue("href", "");
                if (href.IsNull())
                {
                    continue;
                }
                if (href.IndexOf(":") < 0)
                {
                    href = string.Format("http://www.xiumm.cc{0}", href);
                }
                objTargetInfo.CatchUrls.Add(href);
            }
            return objTargetInfo;
        }

        protected override void SaveImagesFromCatch(JiaLiContext objJiaLiContext, string catchUrl)
        {
            if (catchUrl.IsNull())
            {
                throw new ArgumentNullException("catchUrl");
            }
            if (objJiaLiContext.IsStop)
            {
                return;
            }
            SourceInfo objFromSource = this.GetSourceInfo(objJiaLiContext, catchUrl);
            if (objFromSource == null)
            {
                this.ShowMessage("请求地址【" + catchUrl + "】没有捕获到可以下载的图片");
                return;
            }

            objFromSource.FromSource = objFromSource;

            var objPageHtmlNodeCollection = objFromSource.HtmlDocument.DocumentNode.SelectNodes("//div[@class='paginator']/a");
            if (objPageHtmlNodeCollection.IsNull())
            {
                return;
            }
            string result = objPageHtmlNodeCollection.Last().InnerText;
            if (result.IsNull())
            {
                return;
            }
            int pageCount = Convert.ToInt32(result.MatchValue(@"\d+", RegexOptions.None));


            SourceInfo objSourceInfo = null;

            for (int i = 1; i < pageCount + 1; i++)
            {
                if (objJiaLiContext.IsStop)
                {
                    break;
                }
                if (i == 1)
                {
                    this.SaveImagesFromSource(objJiaLiContext, objFromSource);
                }
                else
                {
                    objSourceInfo = this.GetSourceInfo(objJiaLiContext, catchUrl.Replace(".html", string.Format("-{0}.html", i)));
                    objSourceInfo.FromSource = objFromSource;

                    this.SaveImagesFromSource(objJiaLiContext, objSourceInfo);
                }
                Thread.Sleep(300);
            }
        }
    }
}
